<template>
	<view class="u-upload-file" @click="upload">
		<view class="loading" v-if="showLoading">
			<view class="loading-box">
				<u-loading :show="showLoading"></u-loading>
			</view>
		</view>
		<slot></slot>
	</view>
</template>

<script setup lang="ts">
	import { ref } from 'vue'
	import { useAuthStore } from '@/store/auth'
	import { storage, tip } from '@/utils'
	
	const showLoading = ref(false)
	const authStore = useAuthStore()
	const props = withDefaults(defineProps<{
		count?:number
	}>(), {
		count:9
	})
	
	const chooseImageSuccess = (data:any) => {
		const domain = import.meta.env.VITE_APP_DOMAIN
		const baseApi = import.meta.env.VITE_APP_BASE_API
		
		const token = authStore.token || storage.getLocalStorage('token')
		showLoading.value = true
		uni.uploadFile({
			filePath:data.path,
			name:'file',
			url:domain + baseApi + '/file/upload',
			header: {
				"Content-type":"multipart/form-data",
				"Authorization": "Bearer " + token
			},
			success:(res1:any) => {
				const t = setTimeout(() => {
					showLoading.value = false
					if(res1.statusCode == 200) {
						const data = JSON.parse(res1.data)
						if(data.code == 200) {
							emit('click', data.data)
						} else {
							tip.showToast(data.msg)
						}
					} else {
						tip.showToast(res1.errMsg)
					}
					clearTimeout(t)
				}, 500)
			}
		})
	}
	
	const emit = defineEmits(['click'])
	const upload = () => {
		// #ifdef APP-PLUS || H5
			uni.chooseImage({
				count:props.count,
				sizeType:['original', 'compressed'],
				sourceType:['album', 'camera'],
				success: (res: any) => {
					if(res.errMsg == 'chooseImage:ok') {
						const path = res.tempFiles[0].path
						chooseImageSuccess({path:path})
					} else {
						console.log(JSON.stringify(res.errMsg))
					}
					
				}
			})
		//#endif
		//#ifdef MP-WEIXIN
		uni.chooseMedia({
			count:props.count,
			mediaType:['image'],
			sizeType:['original', 'compressed'],
			sourceType:['album', 'camera'],
			success: (res: any) => {
				if(res.errMsg == 'chooseMedia:ok') {
					const path = res.tempFiles[0].tempFilePath
					chooseImageSuccess({path:path})
				} else {
					console.log(JSON.stringify(res.errMsg))
				}
			}
		})
		//#endif
	}
</script>

<style lang="scss" scoped>
	.u-upload-file {
		width:100%;
		height:100%;
		position:relative;
		.loading {
			width:100%;
			height:100%;
			background-color: rgba(0,0,0,0.1);
			z-index:99;
			position:absolute;
			.loading-box {
				position:absolute;
				top:50%;
				left:50%;
				transform: translate(-50%, -50%);
			}
		}
	}
</style>